<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 图片上传
 *
 * @author      Eden
 * @datetime    2016/11/30 23:32
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Image_Model extends API_Model
{
    private $field = 'file';
    private $width = 0;
    private $height = 0;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run($params = array())
    {
        $send['state'] = false;
        do {

            if ($this->input->method(true) !== 'POST') {
                $send['error'] = '非法请求';
                break;
            }

            if (empty($_FILES)) {
                $send['error'] = '没有图片被上传';
                break;
            }

            if (!empty($params['field'])) {
                $this->field = value($params, 'field', 'file');
            }

            $res = local($_FILES[$this->field]);
            if (!$res) {
                $send['error'] = '上传失败';
                break;
            }

            // 如果设置了宽度
            if (isset($params['width']) && isset($params['height'])) {
                $width = intval($params['width']);
                $height = intval($params['height']);
                if (!empty($width) && !empty($height)) {
                    $this->width = $width;
                    $this->height = $height;
                }
            }

            $send['state'] = true;

            $return['key'] = value($res, 'key');
            $return['view'] = array(
                'thumbPath' => thumb($res['key'], $this->width, $this->height),
                'fullPath' => thumb($res['key'])
            );

            $send['data'] = $return;
        } while(false);

        $this->output->send($send);
    }
}
